package com.ellecity06.cwhiskymall.ui.address

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.cwhiskymall.bean.request.AddressEditRequest
import com.ellecity06.cwhiskymall.http.request
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/31 11:31
 * @des
 */
class AddressManagerViewModel : BaseMviViewModel<AddressManagerState, AddressManagerIntent>() {
    override suspend fun collectIntent(it: AddressManagerIntent) {
        when (it) {
            is AddressManagerIntent.RefreshData -> {
                fetchAddressList()
            }
            is AddressManagerIntent.DeleteAddress ->  {
                deleteAddress(it.id)
            }
            is AddressManagerIntent.SetDefaultAddress -> {
              setDefault(it.id)
            }
        }
    }

    private fun setDefault(id: Int) {
        request(api ={setDefaultAddress(AddressEditRequest(id))}, showLoading = true, success = {
            fetchAddressList()
        } )
    }
    private fun deleteAddress(id: Int) {
        request(api ={deleteAddress(AddressEditRequest(id))}, showLoading = true, success = {
            fetchAddressList()
        } )
    }
    private fun fetchAddressList() {
        request(api = { addressList() }, success = {
            mState.postEvent(AddressManagerState.FetchDataSuccess(it!!))
        }, error = {
            viewModelScope.launch {
                mState.postEvent(AddressManagerState.LoadDataError)
            }
        })
    }
}